package com.howard.modules.base.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.howard.base.util.StringUtil;
import com.howard.modules.base.dao.AppBaseDao;
import com.howard.modules.base.paging.Paging;

public abstract class AppBaseDaoImpl<T> extends HibernateDaoSupport implements AppBaseDao<T> {
	
    @Resource(name = "sessionFactory")
    public void init(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }
	  
    protected Class<T> domainClass = getDomainClass();

    /** 日志对象 */
    protected Logger logger = Logger.getLogger(this.getClass());

    public abstract Class<T> getDomainClass();

    @SuppressWarnings("unchecked")
    public T load(String id) {
        return (T) getHibernateTemplate().get(domainClass, id);
    }

    @SuppressWarnings("unchecked")
    public T load(String id, LockMode lockMode) {
        return (T) getHibernateTemplate().get(domainClass, id, lockMode);
    }

    @SuppressWarnings("unchecked")
    public T load(int id) {
        return (T) getHibernateTemplate().get(domainClass, id);
    }

    public void update(T t) {
        getHibernateTemplate().update(t);
    }

    public void merge(T t) {
        getHibernateTemplate().merge(t);
    }

    public void save(T t) {
        getHibernateTemplate().save(t);
    }

    public void delete(T t) {
        getHibernateTemplate().delete(t);
    }

    @SuppressWarnings("unchecked")
    public List<T> getList() {
        return (getHibernateTemplate().find("from " + domainClass.getName() + " x"));
    }

    public void flush() {
        this.getHibernateTemplate().flush();
    }
    
    public void deleteById(String id) {
    	Object obj = load(id);
    	getHibernateTemplate().delete(obj);
    	
    }
    
	@Override
	public void saveOrUpdate(T t) {
		getHibernateTemplate().saveOrUpdate(t);
	}
	
	
	@Override
	public List<T> getList(String str, Map<String, String> values) {
		return null;
	}

    @SuppressWarnings("unchecked")
    public List<T> getList(final Paging page) {
        return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery("from " + domainClass.getName() + " x");
                return query.setFirstResult(page.getStartRow()).setMaxResults(page.getPageSize()).list();
            }
        });
    }


    public void deleteAll() {
        getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                String hqlDelete = "delete " + domainClass.getName();
                session.createQuery(hqlDelete).executeUpdate();
                return null;
            }

        });
    }

    @SuppressWarnings("unchecked")
    public int count() {
        List<T> list = getHibernateTemplate().find("select count(*) from " + domainClass.getName() + " x");
        return Integer.parseInt(list.get(0).toString());
    }

    /**
     * 条件查询时使用，获得满足条件的记录总数。
     * @param str
     * @param values
     * @return
     */
    public int count(final String str, final Map<String, String> values) {
        return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                String sqlString = "select count(*) ";
                Query query = session.createQuery(sqlString + str);
                if (!StringUtil.isBlank(values)) {
                    Set<String> keys = values.keySet();
                    for (String key : keys) {
                        query.setString(key, values.get(key));
                    }
                }
                return Integer.valueOf(query.uniqueResult().toString()).intValue();
            }
        });

    }

    @SuppressWarnings("unchecked")
    public List<T> getList(final String str, final Map<String, String> values, final Paging page) {
        return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(str);
                if (!StringUtil.isBlank(values)) {
                    Set<String> keys = values.keySet();
                    for (String key : keys) {
                        query.setString(key, values.get(key));
                    }
                }
                if (page == null) {
                    return query.list();
                } else {
                    return query.setFirstResult(page.getStartRow()).setMaxResults(page.getPageSize()).list();
                }
            }
        });
    }

  

    /**
     * 条件查询时使用，获得满足条件的记录总数。
     * @param str
     * @param values
     * @return
     * @history kim.cheng 2012-5-28 新增
     */
    public int queryCount(final String str, final Map<String, Object> values) {
        return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                String sqlString = "select count(*) ";
                Query query = session.createQuery(sqlString + str);
                if (!StringUtil.isBlank(values)) {
                    Set<String> keys = values.keySet();
                    for (String key : keys) {
                        query.setParameter(key, values.get(key));
                    }
                }
                return Integer.valueOf(query.uniqueResult().toString()).intValue();
            }
        });

    }

    /**
     * 条件查询时使用，获得满足条件的记录总数。
     * @param str
     * @param values
     * @return
     * @history kim.cheng 2012-5-28 新增
     */
    @SuppressWarnings("unchecked")
    public List<T> queryList(final String str, final Map<String, Object> values, final Paging page) {
        return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(str);
                if (!StringUtil.isBlank(values)) {
                    Set<String> keys = values.keySet();
                    for (String key : keys) {
                        query.setParameter(key, values.get(key));
                    }
                }
                if (page == null) {
                    return query.list();
                } else {
                    return query.setFirstResult(page.getStartRow()).setMaxResults(page.getPageSize()).list();
                }
            }
        });
    }

    /**
     * 执行SQL更新语句
     */
    public int executeSQLUpdate(final String sql, final Object[] args) {
        return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
            @SuppressWarnings("deprecation")
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Connection conn = null;
                PreparedStatement pstmt = null;
                try {
                    // 设置数据库连接
                    // conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
                    conn = session.connection();
                    pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                    // 设置查询参数
                    if (args != null) {
                        for (int i = 0, iSize = args.length; i < iSize; i++) {
                            pstmt.setObject(i + 1, args[i]);
                        }
                    }
                    int result = pstmt.executeUpdate();
                    return result;
                } catch (SQLException ex) {
                    logger.error("执行自定义更新语句出错 ", ex);
                    throw ex;
                } finally {
                    JdbcUtils.closeConnection(pstmt, conn);
                }
            }
        });
    }

    /**
     * 条件查询时使用，获得满足条件的记录总数。
     */
    public int queryCountBySQL(final String str, final Object[] args) {
        return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(str);
                if (args != null) {
                    for (int i = 0; i < args.length; i++) {
                        query.setParameter(i, args[i]);
                    }
                }
                return Integer.valueOf(query.uniqueResult().toString()).intValue();
            }
        });

    }

    /**
     * 条件查询时使用，获得满足条件的记录总数。
     */
    @SuppressWarnings("unchecked")
    public List<T> queryListBySQL(final String str, final Object[] args, final Paging page) {
        Object o = getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                SQLQuery query = session.createSQLQuery(str);
                if (args != null) {
                    for (int i = 0; i < args.length; i++) {
                        query.setParameter(i, args[i]);
                    }
                }
                query.addEntity(getDomainClass());
                if (page == null) {
                    return query.list();
                } else {
                    return query.setFirstResult(page.getStartRow()).setMaxResults(page.getPageSize()).list();
                }
            }
        });
        return (List<T>) o;
    }

    /**
     * 查询单列
     */
    @SuppressWarnings("unchecked")
    public List<Object> singleQueryBySQL(final String str, final Object[] args, final Paging page) {
        Object rs = getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                SQLQuery query = session.createSQLQuery(str);
                if (args != null) {
                    for (int i = 0; i < args.length; i++) {
                        query.setParameter(i, args[i]);
                    }
                }
                if (page == null) {
                    return query.list();
                } else {
                    return query.setFirstResult(page.getStartRow()).setMaxResults(page.getPageSize()).list();
                }
            }
        });
        List<Object> lstObject = rs == null ? new ArrayList<Object>(0) : (List<Object>) rs;
        return lstObject;
    }


}
